﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

public class ConnectPingController:ISocketServer,IClientsManagerListener
{
    ServerSocket m_PingSocket;

    TCPClientsManager m_TCPClientsManager;

    public void Start(bool udp,int port)
    {
        if (udp)
        {
            m_PingSocket = new UDPSocketServer(this);
            m_PingSocket.Start(port, 65534);
            m_PingSocket.BeginReceive();
        }
        else
        {
            m_TCPClientsManager = new TCPClientsManager();
            m_TCPClientsManager.Start(port, 65534);
            m_TCPClientsManager.listener = this;
            m_TCPClientsManager.offlineWaitSceonds = 1;
        }

        GameDebug.Log($"ConnectPingController  Start:{port}");
    }

    void ISocketServer.OnReceiveData(EndPoint endPoint, byte[] data)
    {
        GameDebug.Log($"收到UDP ping:{endPoint}");

        if (data.Length == 1 && data[0] == ServerConfig.ConnectPingByte)
        {
            GameDebug.Log($"m_PingSocket _SendData endPoint:{endPoint}");

            m_PingSocket._SendData(new byte[] { ServerConfig.ConnectPingByte }, endPoint);
        }
        else
        {
            GameDebug.Log($"非协议数据:{BitConverter.ToString(data)}");
        }
    }

    void ISocketServer.OnRecOrSendFailed(EndPoint endPoint)
    {
        GameDebug.Log($"OnRecOrSendFailed  endPoint:{endPoint}");
    }
    

    void IClientsManagerListener.OnDisConnect(Remote remote)
    {

    }

    void IClientsManagerListener.OnNewClient(Remote remote)
    {
        remote.receiveDataHandler = (data) =>
        {
            GameDebug.Log("收到TCP ping");

            if (data.Length == 1 && data[0] == ServerConfig.ConnectPingByte)
            {
                remote.SendData(new byte[] { ServerConfig.ConnectPingByte });
            }
            else
            {
                GameDebug.Log($"非协议数据:{BitConverter.ToString(data)}");
            }
        };
    }

}